package com.xuetang.service.impl;

import com.xuetang.entity.SysUser;
import com.xuetang.mapper.UserMapper;
import com.xuetang.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户服务实现类
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RestTemplate restTemplate;

    @Value("${xuetang.wx.appid}")
    private String appid;

    @Value("${xuetang.wx.secret}")
    private String secret;

    @Value("${xuetang.wx.login-url}")
    private String loginUrl;

    @Override
    public Map<String, Object> wxLogin(String code) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 调用微信登录接口
            String url = String.format(loginUrl, appid, secret, code);
            Map<String, Object> wxResponse = restTemplate.getForObject(url, Map.class);

            if (wxResponse != null && wxResponse.get("openid") != null) {
                String openid = (String) wxResponse.get("openid");

                // 查询用户是否存在
                SysUser user = getByOpenid(openid);

                // 不存在则创建新用户
                if (user == null) {
                    user = new SysUser();
                    user.setOpenid(openid);
                    user.setCreateTime(LocalDateTime.now());
                    user.setStatus(1);
                    userMapper.insert(user);
                }

                // 更新最后登录时间
                user.setLastLoginTime(LocalDateTime.now());
                userMapper.update(user);

                // 生成token
                String token = "mock_token_" + openid; // 实际应使用JWT生成

                result.put("code", 0);
                result.put("message", "登录成功");
                result.put("token", token);
                result.put("userInfo", user);
            } else {
                result.put("code", 1);
                result.put("message", "微信登录失败");
            }
        } catch (Exception e) {
            result.put("code", 1);
            result.put("message", "登录异常: " + e.getMessage());
        }

        return result;
    }

    @Override
    public SysUser getById(Long id) {
        return userMapper.getById(id);
    }

    @Override
    public SysUser getByOpenid(String openid) {
        return userMapper.getByOpenid(openid);
    }

    @Override
    @Transactional
    public boolean update(SysUser user) {
        user.setUpdateTime(LocalDateTime.now());
        return userMapper.update(user) > 0;
    }

    @Override
    @Transactional
    public boolean updateStatus(Long id, Integer status) {
        SysUser user = getById(id);
        if (user == null) {
            return false;
        }

        user.setStatus(status);
        user.setUpdateTime(LocalDateTime.now());

        return userMapper.update(user) > 0;
    }

    @Override
    public List<SysUser> listWxUsers(String keyword, Integer diabetesType, Integer status, Integer page, Integer size) {
        // 实际应该使用分页查询
        // 此处简单实现，返回所有用户
        List<SysUser> users = userMapper.list();

        // 过滤数据
        List<SysUser> result = new ArrayList<>();
        for (SysUser user : users) {
            // 关键字过滤
            if (keyword != null && !keyword.isEmpty()) {
                if ((user.getNickname() != null && user.getNickname().contains(keyword)) ||
                        (user.getUsername() != null && user.getUsername().contains(keyword))) {
                    // 匹配
                } else {
                    continue;
                }
            }

            // 糖尿病类型过滤
            if (diabetesType != null && !diabetesType.equals(user.getDiabetesType())) {
                continue;
            }

            // 状态过滤
            if (status != null && !status.equals(user.getStatus())) {
                continue;
            }

            result.add(user);
        }

        return result;
    }

    @Override
    public Map<String, Object> getUserStats() {
        Map<String, Object> stats = new HashMap<>();

        // 总用户数
        int totalUsers = userMapper.count();
        stats.put("totalUsers", totalUsers);

        // 今日新增用户数
        int todayNewUsers = userMapper.countTodayNewUsers();
        stats.put("todayNewUsers", todayNewUsers);

        // 按糖尿病类型统计
        int type1Users = userMapper.countByDiabetesType(1);
        int type2Users = userMapper.countByDiabetesType(2);
        stats.put("type1Users", type1Users);
        stats.put("type2Users", type2Users);

        return stats;
    }

    @Override
    @Transactional
    public boolean updateNickname(Long id, String nickname) {
        SysUser user = getById(id);
        if (user == null) {
            return false;
        }

        user.setNickname(nickname);
        user.setUpdateTime(LocalDateTime.now());

        return userMapper.update(user) > 0;
    }

    @Override
    @Transactional
    public boolean updateAvatar(Long id, String avatar) {
        SysUser user = getById(id);
        if (user == null) {
            return false;
        }

        user.setAvatar(avatar);
        user.setUpdateTime(LocalDateTime.now());

        return userMapper.update(user) > 0;
    }
}